<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <title>预加载</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css/style.css">
  <!-- Vue 3 & Element Plus -->
  <script src="./public/vue.global.prod.js"></script>
  <!-- 引入 Element Plus -->
  <link rel="stylesheet" href="./public/element-plus-index.css">
  <script src="./public/index.full.js"></script>
  <link rel="stylesheet" href="./public/icon.css" />
  <!-- ECharts -->
  <script src="./public/echarts.min.js"></script>
  <script src="./public/axios.min.js"></script>
  <style>
    .breadcrumb {
      margin-bottom: 30px;
    }

    .search-bar {
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .add-btn {
      margin-bottom: 16px;
    }

    .el-table th,
    .el-table td {
      text-align: center;
    }

    .modal-table-title {
      margin: 18px 0 8px 0;
      font-size: 16px;
      color: #333;
      font-weight: 500;
      border-bottom: 1px solid #eee;
      padding-bottom: 6px;
    }
  </style>
</head>

<body>
  <div id="app">
    <div class="container">
      <el-breadcrumb class="breadcrumb" separator="/">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>预启动管理</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="search-bar">
        <el-form :inline="true" @submit.prevent>
          <el-form-item label="服务器IP">
            <el-input v-model="searchIp" placeholder="请输入服务器Ip" clearable style="width: 220px;"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-button class="add-btn" type="primary" @click="showModal = true">添加</el-button>

      <el-table :data="filteredData" border style="width: 100%; margin-bottom: 16px;">
        <el-table-column prop="name" label="应用名称" min-width="100"></el-table-column>
        <el-table-column prop="ip" label="服务器Ip" min-width="120"></el-table-column>
        <el-table-column prop="count" label="预启动数量" min-width="100"></el-table-column>
        <el-table-column prop="bitrate" label="码率" min-width="80"></el-table-column>
        <el-table-column prop="framerate" label="帧率" min-width="80"></el-table-column>
        <el-table-column prop="restart" label="退出重启应用" min-width="100"></el-table-column>
        <el-table-column prop="running" label="服务器运行数" min-width="100"></el-table-column>
        <el-table-column prop="using" label="正在使用数" min-width="100"></el-table-column>
        <el-table-column prop="status" label="状态" min-width="80"></el-table-column>
        <el-table-column label="操作" min-width="140">
          <template #default="scope">
            <el-button type="danger" size="small" @click="deleteRow(scope.$index)">删除</el-button>
            <el-button type="warning" size="small" @click="disableRow(scope.$index)">禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="filteredData.length === 0" style="color:#888; text-align:center; margin-bottom:16px;">
        暂无数据
      </div>

      <el-pagination layout="total, sizes, prev, pager, next" :total="filteredAllData.length" :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50, 100]" :current-page="currentPage" @current-change="handlePageChange"
        @size-change="handleSizeChange" background size="small" hide-on-single-page="true"></el-pagination>
      <!-- 添加弹窗 -->
      <el-dialog v-model="showModal" title="添加预启动应用" width="800px" :close-on-click-modal="false"
        :close-on-press-escape="false" @open="onDialogOpen">
        <el-form :model="modalForm" label-width="80px" style="margin-bottom: 16px;">
          <el-form-item label="应用" required>
            <el-select v-model="modalForm.name" placeholder="请选择" @change="onAppChange">
              <el-option v-for="app in appList" :key="app" :label="app" :value="app"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="modal-table-title">预启动服务器</div>
        <el-table :data="modalServers" border style="width: 100%; margin-bottom: 18px;">
          <el-table-column label="服务器IP">
            <template #default="scope">
              <el-input v-model="scope.row.ip" placeholder="IP"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="预启动数量">
            <template #default="scope">
              <el-input v-model="scope.row.count" placeholder="数量"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="码率">
            <template #default="scope">
              <el-input v-model="scope.row.bitrate" placeholder="码率"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="帧率">
            <template #default="scope">
              <el-input v-model="scope.row.framerate" placeholder="帧率"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="自动调整">
            <template #default="scope">
              <el-select v-model="scope.row.autoAdjust" placeholder="请选择">
                <el-option label="是" value="是"></el-option>
                <el-option label="否" value="否"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="退出重启应用">
            <template #default="scope">
              <el-select v-model="scope.row.restart" placeholder="请选择">
                <el-option label="是" value="是"></el-option>
                <el-option label="否" value="否"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="最小值">
            <template #default="scope">
              <el-input v-model="scope.row.min" placeholder="最小值"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="最大值">
            <template #default="scope">
              <el-input v-model="scope.row.max" placeholder="最大值"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="最小空闲数">
            <template #default="scope">
              <el-input v-model="scope.row.minIdle" placeholder="最小空闲数"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="最大空闲数">
            <template #default="scope">
              <el-input v-model="scope.row.maxIdle" placeholder="最大空闲数"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="犹豫时间">
            <template #default="scope">
              <el-input v-model="scope.row.hesitate" placeholder="犹豫时间"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeServer(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
          <template #empty>
            <div style="color:#888;">暂无数据</div>
          </template>
        </el-table>
        <template #footer>
          <el-button type="primary" @click="onAdd">确定</el-button>
          <el-button @click="closeModal">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
  <script>
    const { createApp, ref, computed, watch, onMounted } = Vue
    function getToken () {
      return sessionStorage.getItem('token')
    }
    async function fetchAppList () {
      try {
        const res = await axios.get('/app', {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': getToken()
          }
        })
        if (res.data.status === 'OK' && Array.isArray(res.data.entities)) {
          // 返回应用名数组
          return res.data.entities.map(item => item.appName)
        } else {
          return []
        }
      } catch (e) {
        console.error('获取应用列表失败', e)
        return []
      }
    }

    createApp({
      setup () {
        // 数据
        const data = ref([
          {
            name: '新庄矿',
            ip: '192.168.1.101',
            count: '2台',
            bitrate: '8000k',
            framerate: '60帧',
            restart: '否',
            running: 2,
            using: 1,
            status: '启用'
          },
          {
            name: '测试应用',
            ip: '192.168.1.102',
            count: '3台',
            bitrate: '6000k',
            framerate: '30帧',
            restart: '是',
            running: 3,
            using: 2,
            status: '启用'
          },

          {
            name: '大数据平台',
            ip: '192.168.1.106',
            count: '5台',
            bitrate: '8000k',
            framerate: '60帧',
            restart: '是',
            running: 5,
            using: 4,
            status: '启用'
          },
          {
            name: '新庄矿',
            ip: '192.168.1.107',
            count: '2台',
            bitrate: '4000k',
            framerate: '30帧',
            restart: '否',
            running: 2,
            using: 0,
            status: '禁用'
          },

        ])
        const searchIp = ref('')
        const showModal = ref(false)
        const appList = ref([])
        const modalForm = ref({
          name: ''
        })
        const modalServers = ref([])
        const currentPage = ref(1)
        const pageSize = ref(10)

        onMounted(async () => {
          appList.value = await fetchAppList()
        })
        const filteredAllData = computed(() => {
          let result = data.value
          if (searchIp.value) {
            result = result.filter(item => item.ip.includes(searchIp.value))
          }
          return result
        })

        const maxPage = computed(() =>
          Math.max(1, Math.ceil(filteredAllData.value.length / pageSize.value))
        )

        const filteredData = computed(() => {
          const start = (currentPage.value - 1) * pageSize.value
          return filteredAllData.value.slice(start, start + pageSize.value)
        })

        function handlePageChange (page) {
          currentPage.value = page
        }
        function handleSizeChange (size) {
          pageSize.value = size
          currentPage.value = 1
        }

        // 保证分页不越界
        watch(filteredAllData, () => {
          if (currentPage.value > maxPage.value) currentPage.value = maxPage.value
        })

        // 查询
        function onSearch () {
          // 过滤自动响应，无需额外处理
        }

        // 删除
        function deleteRow (idx) {
          ElementPlus.ElMessageBox.confirm('确定要删除该条记录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            const item = filteredData.value[idx]
            data.value = data.value.filter(d => d !== item)
            ElementPlus.ElMessage.success('删除成功')
          }).catch(() => { })
        }

        // 禁用
        function disableRow (idx) {
          filteredData.value[idx].status = '禁用'
        }

        // 关闭弹窗
        function closeModal () {
          showModal.value = false
          modalForm.value.name = ''
          modalServers.value = []
        }

        // 弹窗打开时清空
        function onDialogOpen () {
          modalForm.value.name = ''
          modalServers.value = []
        }

        // 删除一行服务器
        function removeServer (idx) {
          modalServers.value.splice(idx, 1)
        }

        // 选择应用时获取数据
        async function onAppChange (appName) {
          modalServers.value = [] // 先清空
          if (!appName) return
          const servers = await fetchAppPreloadServers(appName)
          if (servers.length > 0) {
            modalServers.value = servers
          } else {
            modalServers.value = [
              {
                ip: '',
                count: '',
                bitrate: '',
                framerate: '',
                autoAdjust: '否',
                restart: '否',
                min: '',
                max: '',
                minIdle: '',
                maxIdle: '',
                hesitate: ''
              }
            ]
          }
        }

        // 添加
        function onAdd () {
          if (!modalForm.value.name) {
            ElementPlus.ElMessage.error('请选择应用')
            return
          }
          if (modalServers.value.length === 0) {
            ElementPlus.ElMessage.error('请添加至少一台服务器')
            return
          }
          modalServers.value.forEach(server => {
            data.value.push({
              name: modalForm.value.name,
              ip: server.ip,
              count: server.count,
              bitrate: server.bitrate,
              framerate: server.framerate,
              restart: server.restart,
              running: server.count,
              using: 0,
              status: '启用'
            })
          })
          closeModal()
          ElementPlus.ElMessage.success('添加成功')
        }

        return {
          data,
          searchIp,
          showModal,
          appList,
          modalForm,
          modalServers,
          filteredData,
          onSearch,
          deleteRow,
          disableRow,
          closeModal,
          removeServer,
          onAdd,
          onAppChange,
          onDialogOpen,
          currentPage,
          pageSize,
          handlePageChange,
          filteredAllData,
          handleSizeChange,
          appList,
          fetchAppList
        }
      }
    }).use(ElementPlus).mount('#app');
  </script>
</body>

</html>